/**
 * 监听并收集页面资源加载失败和加载缓慢的情况
 * @param {Page} page - Puppeteer页面实例
 * @returns {Object} 返回包含失败请求和慢请求的数组
 */
export async function getFailedResources(page) {
  const failedRequests = [];
  const slowRequests = [];
  
  // 监听请求失败事件
  page.on('requestfailed', request => {
    failedRequests.push({
      url: request.url(),
      errorText: request.failure().errorText,
    });
  });

  // 监听请求完成事件，使用responseEnd - requestStart 计算请求时间
  page.on('requestfinished', async request => {
    const response = await request.response();
    if (response) {
      const timing = await response.timing();
      if (timing) {
        const duration = timing.responseEnd - timing.requestStart;
        if (duration > 1000) {  // 超过1秒的请求
          slowRequests.push({
            url: request.url(),
            duration: Math.round(duration),
          });
        }
      }
    }
  });

  return { failedRequests, slowRequests };
} 